package net.src.tcp_sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务端tcp通信
 */
public class ServerDemo2 {
    //定义一个静态的list集合存储当前所有在线的socket
    public static List<Socket> allOnlineSockets = new ArrayList<>();
    public static void main(String[] args) throws Exception {
        System.out.println("服务器启动成功!");
        //注册端口
        ServerSocket serverSocket = new ServerSocket(8888);

        //循环接收客户端的socket请求
        while(true){
            Socket socket = serverSocket.accept();
            System.out.println(socket.getRemoteSocketAddress() + "已经上线!");
            allOnlineSockets.add(socket);//上线完成
            new ServerReaderThread(socket).start();
        }

    }
}

class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //socket获取字节流,字节流包装成字符流,再包装成字符缓冲流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while((msg = br.readLine())!=null){
                System.out.println(socket.getRemoteSocketAddress() + ":" + msg);
                //把消息转发给所有的客户端
                sendMsgToAll(socket,msg);
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress() + "已经下线");
            ServerDemo2.allOnlineSockets.remove(socket);//下线操作
        }
    }

    private void sendMsgToAll(Socket socket,String msg) throws Exception {
        for (Socket eachSocket : ServerDemo2.allOnlineSockets) {
            if(socket!=eachSocket){
                PrintStream ps = new PrintStream(eachSocket.getOutputStream());
                ps.println(msg);
                ps.flush();
            }
        }
    }
}